package auction.serveroutage;


import java.io.*;
import java.net.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64;

import auction.client.Client;


public class TimeStampSession extends Thread {
	public Logger log = Logger.getLogger(TimeStampSession.class);

	private Socket socket;
	private PrintWriter out;
	private BufferedReader in;
	private String command;


	public TimeStampSession (Socket s)throws IOException{
		this.socket=s;
	
		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));

		} catch (IOException e) {
			cleanUp();
			throw e;
		}

	}
	public void run(){
		
		try{
			//read command
			command = in.readLine();
			
			while (command!=null){

				
				if(command.startsWith("!getTimestamp")){
					
					log.debug("Incoming command: "+command);
					
					String[] s = command.split(" ");
					String aucionId = s[1];
					String price = s[2];
					
					//send back	
					//format: "!timestamp <auctionID> <price> <timestamp> <signature>"
					String sendString = "!timestamp "+aucionId+" "+price+" "+System.currentTimeMillis();
					byte[] base64Signature = null;
					// sign 
					try {
						
						Signature instance = Signature.getInstance("SHA512withRSA");
						instance.initSign(Client.getPrivateKey());
						instance.update(sendString.getBytes()); // String being sign
						byte[] signature = instance.sign(); // signature as byte[] 
						base64Signature = Base64.encode(signature); //encode Base64
						
					} catch (InvalidKeyException e) {
						log.debug("Error: "+e.getMessage());
					} catch (SignatureException e) {
						log.debug("Error: "+e.getMessage());
					} catch (NoSuchAlgorithmException e) {
						log.debug("Error: "+e.getMessage());
					}
					
					String signString = new String(base64Signature);
					
					out.println(sendString+" "+signString);//format: "!timestamp <auctionID> <price> <timestamp> <signature>"
				}
				
				//read next command
				command = in.readLine();
		

			}

		} catch (IOException e) {
			System.out.println("Client error.");
			cleanUp();
		}
	}

	private void cleanUp() {
		try {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				out.close();
			}
			socket.close();
		} catch (IOException e) {
			/* ignore */
		}
	}




}
